from ctypes import windll, byref
from ctypes.wintypes import RECT
import ctypes
import cv2, dxcam
import numpy as np
import pyautogui
from time import sleep
#from PIL import Image
from findimage import find_template, find_all_template
from sys import exc_info

# 定义鼠标事件的参数
MOUSEEVENTF_LEFTDOWN = 0x0002  # 左键按下
MOUSEEVENTF_LEFTUP = 0x0004  # 左键释放
MOUSEEVENTF_MOVE = 0x0001  # 鼠标移动

# 获取user32.dll和kernel32.dll库的句柄
user32 = ctypes.WinDLL('user32', use_last_error=True)
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

# 定义相关窗口句柄函数和方法
FindWindowA = user32.FindWindowA
GetWindowThreadProcessId = user32.GetWindowThreadProcessId
OpenProcess = kernel32.OpenProcess
CloseHandle = kernel32.CloseHandle
SendMessageA = user32.SendMessageA

wins = []
# 定义函数用于获取指定标题窗口的句柄和位置大小信息
hwnd = windll.user32.FindWindowW(None, "工作簿1 - WPS 表格")
if hwnd:
	rect = RECT()
	windll.user32.GetWindowRect(hwnd, byref(rect))
	# 获取目标窗口的大小
	width = rect.right - rect.left
	height = rect.bottom - rect.top
	wins +=[{"rect":rect, "title":"龙鳞","coords":[(552,316), (587,267)], "last_coord":[0.6, 0.51], "line":4, "turn":0}]
	#_, _, window_x, window_y = user32.GetClientRect(hwnd)
else:
    print(f"Can't find window: “龙鳞”")
    exit()

# 特殊作用坐标
coords_spec={"map":(0.876,0.185), "vip":(0.2,0.26), "checkin":[0.52, 0.82], "hand":(0.97,0.502), "pack":(0.97,0.415), "off":(0.98,0.117), "recycle1":(0.875, 0.925), "recycle2":(0.85, 0.887), "red":(0.452, 0.132), "active":(0.775,0.035), "linesw":(0.95,0.97)}

# 获取目标窗口的进程ID和线程ID
process_id = ctypes.c_ulong()
thread_id = GetWindowThreadProcessId(hwnd, byref(process_id))

# 打开目标进程，获取对进程的句柄
process_handle = OpenProcess(0x1000, False, process_id)
if not process_handle:
    print(f"Can't open process: {process_id}")
    exit()

coord = coords_spec["map"]
x, y = int(coord[0]*width), int(coord[1]*height)  # 坐标换算
print(width, height)
		
# 发送鼠标点击事件
lParam = 1100 | 560 << 16
#wParam = ctypes.windll.user32.MK_LBUTTON
SendMessageA(hwnd, MOUSEEVENTF_LEFTDOWN, 1, lParam)
SendMessageA(hwnd, MOUSEEVENTF_LEFTUP, 0, lParam)

# 关闭句柄
CloseHandle(process_handle)

def back_click(rect: RECT, coord):
	# 屏幕分辨率
	screen_width = 1440 + 1366 # 第一屏+第二屏横向分辨率
	screen_height = 768 #第二屏纵向分辨率
	width = rect.right - rect.left
	height = rect.bottom - rect.top
	if coord[0] < 1: # 比例
		x, y = rect.left + 1440 + int(coord[0]*width), rect.top + int(coord[1]*height)  # 坐标换算
	else: # 直接坐标
		x, y = rect.left + 1440 + coord[0], rect.top + coord[1]
	# 将屏幕坐标转换为规范化绝对坐标
	x = int(x * 65535 / screen_width)
	y = int(y * 65535 / screen_height)
	# 调用mouse_event函数
	windll.user32.mouse_event(32769, x, y, 0, 0)
	sleep(0.5)
	# 按下鼠标左键
	windll.user32.mouse_event(2, 0, 0, 0, 0)
	sleep(0.1)
	# 松开鼠标左键
	windll.user32.mouse_event(4, 0, 0, 0, 0)
	
#back_click(rect, coords_spec["map"])